<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules">
      <el-form-item label="" prop="reason">
        <el-input type="textarea" v-model="formData.reason" placeholder="请输入原因" rows="5" maxlength="500"
        show-word-limit />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">提交</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import * as PublishApi from '@/api/publish/index'
const message = useMessage() // 消息弹窗
const { currentRoute, push, go } = useRouter()
const formLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = ref({
  reason: ''
})
const formRules = reactive({
  reason: [{ required: true, message: '关闭原因不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const publishId = ref()
const publishType = ref('')
/** 打开弹窗 */
const open = async (id, type) => {
  dialogVisible.value = true
  resetForm()
  publishId.value = id
  publishType.value = type
  if (type === 'refuse') {
    dialogTitle.value = '拒绝审核'
  } else {
    dialogTitle.value = '取消发布'
  }
}
const resetForm = () => {
  formData.value = {
    reason: ''
  }
  formRef.value?.resetFields()
}
defineExpose({ open })
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  formLoading.value = true
  try {
    if (publishType.value === 'refuse') {
      await PublishApi.verifyPublish(
        {
          id: publishId.value,
          status: 3,
          reason: formData.value.reason
        }
      )
    } else {
      await PublishApi.cancelRelease(
        {
          id: publishId.value,
          reason: formData.value.reason
        }
      )
    }
    message.success('已提交')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>

<style lang="scss" scoped></style>
